package com.lyons.easyweb.modular.user.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyons.easyweb.exception.BaseResponseCode;
import com.lyons.easyweb.exception.BusinessException;
import com.lyons.easyweb.modular.user.dao.SysUserMapper;
import com.lyons.easyweb.modular.user.pojo.SysUser;
import com.lyons.easyweb.modular.user.service.UserService;
import com.lyons.easyweb.modular.user.vo.req.UserReqVo;
import com.lyons.easyweb.modular.user.vo.resp.LoginRespVo;

import cn.hutool.crypto.SecureUtil;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author HengDuCms
 * @since 2021-06-27
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements UserService {

	// 用户登录
	@Override
	public LoginRespVo login(UserReqVo userReqVo) {

		SysUser user = baseMapper.selectOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getAccount, userReqVo.getAccount()));
		if (ObjectUtils.isEmpty(user)) {
			throw new BusinessException(BaseResponseCode.ACCOUNT_ERROR);
		}
		if (user.getStatus() == 0) {
			throw new BusinessException(BaseResponseCode.ACCOUNT_LOCK);
		}
		// 判断密码
		if (!SecureUtil.md5(userReqVo.getPassword()).equalsIgnoreCase(user.getPassword())) {
			throw new BusinessException(BaseResponseCode.ACCOUNT_PASSWORD_ERROR);
		}

		LoginRespVo loginUser = LoginRespVo.builder().userId(user.getId()).build();
		return loginUser;
	}

	// 用户修改密码
	@Override
	public boolean updatePwd(String oldPassword, String newPassword, String userId) {

		SysUser user = getById(userId);
		// 验证就密码是否正确
		if (!SecureUtil.md5(oldPassword).equalsIgnoreCase(user.getPassword())) {
			throw new BusinessException(4000, "旧密码不对");
		}

		user.setPassword(SecureUtil.md5(newPassword));
		updateById(user);

		return true;
	}

	// 重置用户密码
	@Override
	public void restPassword(String userId) {
		
		
		
	}

}
